#include <stdlib.h>
#include <tchar.h>
void freeargs(int argc,TCHAR **argv)
{
    int i;
    for(i=0;i<argc;i++) free(argv[i]);
    free(argv);
}

int getargs(const TCHAR *cmdline,TCHAR ***pargv)
{
    int len,i,ct=0,mct=0,cch=0,mcch=0,dq=0;
    TCHAR *tmpb=NULL,*tmpbn,**argv,**argvn;

    len=_tcslen(cmdline);
    for(i=0;i<=len;i++) {
        if(cmdline[i]=='\"') {
            if(dq) {
                if(cmdline[i+1]==' ') dq=0;
            } else dq=1;
        } else if(((!dq)&&(cmdline[i]==' '))||(i==len)) {
            if(cch||dq||(i?(cmdline[i-1]=='\"'):0)) {
                if(ct==mct) {
                    mct+=16;
                    argvn=(char **)calloc(mct,sizeof(char *));
                    if(!argvn) {
                        free(tmpb);
                        freeargs(ct,argv);
                        return -1;
                    }
                    if(ct) {
                        memcpy(argvn,argv,ct*sizeof(char *));
                        free(argv);
                    }
                    argv=argvn;
                }
                if(!cch) {
                    tmpb=(char *)malloc(1);
                    if(!tmpb) {
                        freeargs(ct,argv);
                        return -1;
                    }
                    tmpb[0]='\0';
                }
                argv[ct++]=tmpb;
                tmpb=NULL;
                cch=0;
                mcch=0;
            }
        } else {
            if(cch==mcch) {
                mcch+=64;
                tmpbn=(char *)malloc(mcch+1);
                if(!tmpbn) {
                    free(tmpb);
                    freeargs(ct,argv);
                    return -1;
                }
                memset(tmpbn,0,mcch+1);
                if(cch) {
                    memcpy(tmpbn,tmpb,cch);
                    free(tmpb);
                }
                tmpb=tmpbn;
            }
            if(dq&&(cmdline[i]=='\\')&&(cmdline[i+1]=='\"')) tmpb[cch]=cmdline[i+1];
            else tmpb[cch]=cmdline[i];
            cch++;
        }
    }
    if(pargv) *pargv=argv;
    return ct;
}
